/*
 * ShareFolderServiceImpl.java
 * {Description}
 * Copyright by Axon Active Viet Nam
 * Da Nang
 * All rights reserved.
 */
package com.team.cloudsharing.service.sharefolder;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.team.cloudsharing.dao.folder.FolderDAO;
import com.team.cloudsharing.dao.folder.FolderDO;
import com.team.cloudsharing.dao.sharefolder.ShareFolderDAO;
import com.team.cloudsharing.dao.sharefolder.ShareFolderDO;
import com.team.cloudsharing.dao.user.UserDAO;
import com.team.cloudsharing.dao.user.UserDO;
import com.team.cloudsharing.dto.FolderSharing;
import com.team.cloudsharing.dto.User;
import com.team.cloudsharing.service.googlecloudmessage.Content;
import com.team.cloudsharing.service.googlecloudmessage.POST2GCM;
import com.team.cloudsharing.service.mail.MailService;
import com.team.cloudsharing.ultis.Constant;
import com.team.cloudsharing.ultis.Email;

@Service("shareFolderService")
public class ShareFolderServiceImpl implements ShareFolderService{

	final static Logger logger = Logger.getLogger(ShareFolderServiceImpl.class);

	@Autowired
	FolderDAO folderDAO;
	
	@Autowired
	ShareFolderDAO shareFolderDAO;
	
	@Autowired
	UserDAO userDAO;
	
	@Autowired
	MailService mailService;
	
	@Value("${HOMEPAGE_URL}")
	String homepageUrl;
	
	@Override
	public String shareFolderToListUser(FolderSharing folderSharing) {
		String shareStatus = "";
		int countNumberEmailShared = 0;
		UserDO userDO = null;
		ShareFolderDO shareFolderDO = null;
		FolderDO folderDOWasShared = folderDAO.findFolderByFolderUrl(folderSharing.getFolderUrl());
		String[] listUserEmailShared = folderSharing.getListUserEmailShared().split("-|\\,|\\;");
		if (folderDOWasShared != null){
			for (String userEmail : listUserEmailShared) {
				userEmail = userEmail.trim();
				if (Email.validate(userEmail)){
					userDO = userDAO.findUserByUserEmail(userEmail);
					if (userDO != null){
						ShareFolderDO shareFolderDOCheck = shareFolderDAO.findShareFolderByFolderIdAndUserId(folderDOWasShared, userDO);
						String checkConditionShare = checkConditionShare(userDO, shareFolderDOCheck, folderSharing.getUserEmail(), userEmail, folderDOWasShared.getUserDO().getUserEmail());
						if (checkConditionShare == null) {
							shareFolderDO = new ShareFolderDO(folderDOWasShared, userDO, getFolderNameNotDuplicate(folderDOWasShared.getFolderName(), userEmail));
							shareFolderDAO.insertShareFolder(shareFolderDO);
							countNumberEmailShared++;
							sendNotificationSharing(userEmail, folderDOWasShared.getFolderName(), folderSharing.getUserEmail());
							mailService.sendMailShareFolder(userEmail, folderDOWasShared.getFolderId(), folderSharing.getUserEmail());
						}
						else{
							shareStatus += checkConditionShare;
						}
					}
					else{
						String documentUrl = homepageUrl + "sh/" + folderSharing.getFolderUrl();
						mailService.sendLinkToEmail(folderSharing.getUserEmail(), documentUrl, folderSharing.getListUserEmailShared());
					}
				}
				else{
					shareStatus += userEmail + " is invalid.";
				}
			}
			if (countNumberEmailShared > 0){
				folderDOWasShared.setSharedFolder(true);
				folderDAO.updateFolder(folderDOWasShared);
			}
			if (shareStatus == ""){
				shareStatus = Constant.SHARE_FOLDER_SUCCESS;
			}
		}
		return shareStatus;
	}
	
	private String checkConditionShare(UserDO userDO, ShareFolderDO shareFolderDO, String emailShare, String emailReceive, String emailOwnerFolder){
		if (userDO == null){
			return emailReceive + " is not register.";
		}
		if (shareFolderDO != null){
			return emailReceive + " has been shared this folder.";
		}
		if (emailReceive.equals(emailShare)){
			return "Can not share this folder for yourself.";
		}
		if (emailReceive.equals(emailOwnerFolder)){
			return "Can not share this folder for owner.";
		}
		return null;
	}
	
	private String getFolderNameNotDuplicate(String folderName, String userEmail){
		String folderNameReturn = folderName;
		UserDO userDO = userDAO.findUserByUserEmail(userEmail);
		FolderDO folderDO = folderDAO.findFolderByFolderNameAndFolderPathAndUserId(folderNameReturn, "", userDO);
		int i = 1;
		while(folderDO != null){
			folderNameReturn = folderName + " (" + i + ")";
			i++;
			folderDO = folderDAO.findFolderByFolderNameAndFolderPathAndUserId(folderNameReturn, "", userDO);
		}
		
		ShareFolderDO shareFolderDO = shareFolderDAO.findShareFolderByFolderNameAndUserId(folderNameReturn, userDO);
		while(shareFolderDO != null){
			folderNameReturn = folderName + " (" + i + ")";
			i++;
			shareFolderDO = shareFolderDAO.findShareFolderByFolderNameAndUserId(folderNameReturn, userDO);
		}
		return folderNameReturn;
	}
	
	private void sendNotificationSharing(String shareEmails, String folderName, String folderOwnerEmail) {
		Content content = new Content();
		String shareUserName = userDAO.findUserByUserEmail(folderOwnerEmail).getUserName();
		String registrationId = userDAO.findUserByUserEmail(shareEmails).getRegistrationId();
		if (registrationId != null && registrationId != ""){
			String title = "CloudSharing Invitation";
			String body = "You was invited to share folder " + folderName + " by " + shareUserName;
			content.addRegId(registrationId);
			content.createData(title, body);
			POST2GCM.post(Constant.GOOGLE_API_KEY, content);
		}
	}

	@Override
	public List<User> getShareFolderInformation(String userEmail, String folderName, String folderPath) {
		UserDO userDO = userDAO.findUserByUserEmail(userEmail);
		FolderDO folderDO = folderDAO.findFolderByFolderNameAndFolderPathAndUserId(folderName, folderPath, userDO);
		List<User> listUsers = new ArrayList<User>();
		List<ShareFolderDO> listShareFolderDOs = shareFolderDAO.findAllShareFolderByFolderDO(folderDO);
		User user = new User();
		for (ShareFolderDO shareFolderDO : listShareFolderDOs) {
			user = convertUserDOToUser(shareFolderDO.getUserDO());
			user.setRole(Constant.ROLE_CAN_EDIT);
			listUsers.add(user);
		}
		user = convertUserDOToUser(userDO);
		user.setRole(Constant.ROLE_OWNER);
		listUsers.add(0, user);
		return listUsers;
	}

	private User convertUserDOToUser(UserDO userDO) {
		User user = new User();
		user.setUserName(userDO.getUserName());
		user.setUserEmail(userDO.getUserEmail());
		user.setRegistrationId(userDO.getRegistrationId());
		return user;
	}

	@Override
	public void leaveOrUnShareFolder(String userEmailOfRequester, String userEmailOfDocument, String folderName,
			String folderPath, String action) {
		UserDO userDOOfRequester = userDAO.findUserByUserEmail(userEmailOfRequester);
		UserDO userDOOfDocument = userDAO.findUserByUserEmail(userEmailOfDocument);
		FolderDO folderDO = folderDAO.findFolderByFolderNameAndFolderPathAndUserId(folderName, folderPath, userDOOfDocument);
		if (Constant.ACTION_LEAVE.equals(action)) {
			shareFolderDAO.deleteShareFolderByFolderDOAndUserDO(folderDO,userDOOfRequester);
		} else {
			folderDO.setSharedFolder(false);
			folderDAO.updateFolder(folderDO);
			shareFolderDAO.deleteShareFolderByFolderDO(folderDO);
		}
		sendNotificationSynchoronize(userEmailOfDocument);
	}

	@Override
	public void sendNotificationSynchoronize(String userEmail) {
		String registrationId = userDAO.findUserByUserEmail(userEmail).getRegistrationId();
		Content content = new Content();
		if (registrationId != null && registrationId != ""){
			String title = "Synchoronize";
			String body = "Has some change to need to synchoronize";
			content.addRegId(registrationId);
			content.createData(title, body);
			POST2GCM.post(Constant.GOOGLE_API_KEY, content);
		}
	}

	@Override
	public void leaveOrUnShareWeb(String userEmailOfRequester, String folderName, String folderPath) {
		UserDO userDORequester = userDAO.findUserByUserEmail(userEmailOfRequester);
		FolderDO folderDO = folderDAO.findFolderByFolderNameAndFolderPathAndUserId(folderName, folderPath, userDORequester);
		if (folderDO != null){
			folderDO.setSharedFolder(false);
			folderDAO.updateFolder(folderDO);
			shareFolderDAO.deleteShareFolderByFolderDO(folderDO);
		} else{
			ShareFolderDO shareFolderDO = shareFolderDAO.findShareFolderByFolderNameAndUserId(folderName, userDORequester);
			FolderDO realFolderDO = shareFolderDO.getFolderDO();
			shareFolderDAO.deleteShareFolderByFolderDOAndUserDO(realFolderDO, userDORequester);
		}
	}
}
